package cn.allinmd.indi.applymodelxian.model.authenticate.bizz.impl;

import android.content.Context;

import cn.allinmd.indi.applymodelxian.model.authenticate.bizz.IAuthModel;
import cn.allinmd.indi.applymodelxian.model.authenticate.bizz.inner.IUserDao;
import cn.allinmd.indi.applymodelxian.model.authenticate.entity.User;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.SaveListener;

/**
 * @author: XianXueLiang
 * @date: 2016/6/22
 */
public class Auth2Impl implements IAuthModel<User> {

    private final Context context;
    private IUserDao mUserAction;

    public Auth2Impl(Context context) {
        this.context = context;
        mUserAction = new UserDaoImpl(context);
    }

    @Override
    public void login(String name, String pwd, String authenticate,  OnAuthStateListener<User> listener) {

        final IAuthModel.OnAuthStateListener<User> mListener = listener;
        if (mListener == null) {
            throw new RuntimeException(listener.getClass().getName()+" must be implemented,not null!!!");
        }

        final BmobUser user = new BmobUser();
        user.setUsername(name);
        user.setPassword(pwd);
        user.setSessionToken(authenticate);
        user.login(context, new SaveListener() {
            @Override
            public void onSuccess() {
                final String sessionToken = user.getSessionToken();
                mUserAction.queryByname(user.getUsername(), new OnAuthStateListener<User>() {
                    @Override
                    public void success(User user, String accessToken) {
                        mListener.success(user,sessionToken);
                    }

                    @Override
                    public void failure(int code, String msg) {
                        mListener.failure(code,msg);
                    }
                });
            }

            @Override
            public void onFailure(int i, String s) {
                mListener.failure(i,s);
            }
        });

    }

    @Override
    public void register(User user, OnAuthStateListener<User> listener) {
        mUserAction.insert(user,listener);
    }
}
